package Admin;


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.List;
import javax.swing.AbstractButton;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;


import GroupClass.ConnectRMI;
import GroupClass.TownClass;
import Project_etow.EtowInterface;


public class TownFree extends javax.swing.JDialog {

	private int row,dem;
	ConnectRMI connectRMI = new ConnectRMI();
	private String townid ,	townname ,townflonumber;
	private String click1, click2, click3;
	private static String a1, a2, a3;
	private DefaultTableModel dtm;
	private String accountId;
	
	public String getAccountId() {
                return accountId;
        }

        public void setAccountId(String accountId) {
                this.accountId = accountId;
        }
  
    public TownFree(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    @SuppressWarnings("unchecked")
    

    
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tbdulieu = new javax.swing.JTable();
        btnchose = new javax.swing.JButton();
        btnexit = new javax.swing.JButton();
        btnInsert = new javax.swing.JButton();
        btnEdit = new javax.swing.JButton();
        btnDelete = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Town Free");
        
        Object colNames[] = {"", "Town Name", "Number Floor",""};  
  	  	Object[][] data = {};  	  	
	  	dtm = new DefaultTableModel(data,colNames);  
	  	tbdulieu = new JTable(dtm);  
	  	tbdulieu.getTableHeader().setReorderingAllowed(false);
	  	tbdulieu.getColumnModel().getColumn(0).setMaxWidth(80);
  	  	tbdulieu.getColumnModel().getColumn(0).setMinWidth(80);
  	  	tbdulieu.getColumnModel().getColumn(0).setWidth(50);
  	  	
	  	tbdulieu.getColumnModel().getColumn(3).setMaxWidth(0);
  	  	tbdulieu.getColumnModel().getColumn(3).setMinWidth(0);
  		TableColumn tc = tbdulieu.getColumnModel().getColumn(0);  
  	    tc.setCellEditor(tbdulieu.getDefaultEditor(Boolean.class));  
  	    tc.setCellRenderer(tbdulieu.getDefaultRenderer(Boolean.class));  
  	    tc.setHeaderRenderer(new CheckBoxHeader(new MyItemListener()));
  	  	
    	tbdulieu.addMouseListener(new MouseAdapter() {
  			@Override
  			public void mouseClicked(MouseEvent e) {
  				e.consume();
  				row = tbdulieu.getSelectedRow();
  				click1 = tbdulieu.getValueAt(row, 1).toString();
  				click2 = tbdulieu.getValueAt(row, 2).toString();
  				click3 = tbdulieu.getValueAt(row, 3).toString();
  				
  				a1 = click1;
  				a2 = click2;
  				a3 = click3;
  				
  			}

  		});
  	  
  	  try {				 
  	    Registry registry = LocateRegistry.getRegistry(connectRMI.host,connectRMI.port);
            EtowInterface obj=(EtowInterface)registry.lookup(connectRMI.regis);
  			
  		List<GroupClass.TownClass> x =obj.showtownfree();
  			
  		
  		for(GroupClass.TownClass d:x) {
  		townid = d.getIdtown();
        	townname = d.getNametown();
        	townflonumber = d.getNumfloortown();        	
  	    dtm.addRow(new Object[]{new Boolean(false),townname,townflonumber,townid});
  		}							
  			
  		}catch (Exception ex) {
  			ex.printStackTrace();
  		}	  	    
  	    	    
        jScrollPane1.setViewportView(tbdulieu);

        btnchose.setText("Choose Floor");
        btnchose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnchoseActionPerformed(evt);
            }
        });

        btnexit.setText("Exit");
        btnexit.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				setVisible(true);				
			}
		});
        
        btnInsert.setText("Insert");
        btnInsert.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				Insert_Town it = new Insert_Town(null, true);
				it.setCheckvisable("ok");
				it.setVisible(true);
				while (it.isVisible() != true) {
					if (it.getCheckvisable().equals("close")) {
					    reloadtable();
						break;
					}
				}
			}
		});

        btnEdit.setText("Edit");
        btnEdit.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {

				EditTown eT = new EditTown(null, true);
				eT.setCheckedit("ok");
				eT.setVisible(true);
				while (eT.isVisible() != true) {
					if (eT.getCheckedit().equals("close")) {
						reloadtable();
						break;
					}
				}
			}
		});

        btnDelete.setText("Delete");
        btnDelete.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				String result = "";
				int i = JOptionPane.showConfirmDialog(null,
						"Neu Ban Da Chac Chan Hay Chon Ok", null,
						JOptionPane.YES_NO_OPTION);
				if (i == JOptionPane.YES_OPTION) {
					EtowInterface obj = null;
					Registry registry;
					try {
					         registry = LocateRegistry.getRegistry(connectRMI.host,connectRMI.port);
	                                         obj=(EtowInterface)registry.lookup(connectRMI.regis);
						dem = 0;
						for (int j = 0; j < tbdulieu.getRowCount(); j++) {
							if (tbdulieu.getValueAt(j, 0).toString() == "true") {
								try {
									dem += 1;
									result = obj.DeleteTown(tbdulieu.getValueAt(j, 3).toString());
									if(result != "Ok")
									{
										JOptionPane.showMessageDialog(null, "" + tbdulieu.getValueAt(j, 1) + " has been deleted");
									}
									
								} catch (RemoteException e) {
									e.printStackTrace();
								}
							}
						}
						reloadtable();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		});
        
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnchose)
                .addGap(18, 18, 18)
                .addComponent(btnInsert)
                .addGap(18, 18, 18)
                .addComponent(btnEdit)
                .addGap(18, 18, 18)
                .addComponent(btnDelete)
                .addGap(18, 18, 18)
                .addComponent(btnexit)
                .addContainerGap(45, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 156, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnchose)
                    .addComponent(btnInsert)
                    .addComponent(btnEdit)
                    .addComponent(btnDelete)
                    .addComponent(btnexit))
                .addGap(0, 17, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TownFree.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TownFree.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TownFree.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TownFree.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }

        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                TownFree dialog = new TownFree(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
                
            }
        });
    }
    private void reloadtable()
    {
        while (tbdulieu.getRowCount() != 0) {
            dtm.removeRow(0);
        }

        try {                           
            Registry registry = LocateRegistry.getRegistry(connectRMI.host,connectRMI.port);
            EtowInterface obj=(EtowInterface)registry.lookup(connectRMI.regis);
                    
            List<GroupClass.TownClass> x =obj.showtownfree();
                    
            
            for(GroupClass.TownClass d:x) {
                    townid = d.getIdtown();
            townname = d.getNametown();
            townflonumber = d.getNumfloortown();            
            dtm.addRow(new Object[]{new Boolean(false),townname,townflonumber,townid});
            }                                                                       
                    
            }catch (Exception ex) {
                    ex.printStackTrace();
            }

    }
    
    private javax.swing.JButton btnchose;
    private javax.swing.JButton btnexit;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tbdulieu;
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnEdit;
    private javax.swing.JButton btnInsert;
    
    // End of variables declaration

  

    
    private void btnchoseActionPerformed(java.awt.event.ActionEvent evt) {
    	for (int j = 0 ; j < tbdulieu.getRowCount();j++)
		{		
			if(tbdulieu.getValueAt(j, 0).toString() == "true")
			{							
				FloorFree florf = new FloorFree(null,true,tbdulieu.getValueAt(j, 3).toString());
				florf.setTownId(a3);
				florf.setCheckVisable("open");
				florf.setVisible(true);
				while (florf.isVisible() != true) {
                                    if (florf.getCheckVisable().equals("close")) {
                                        if(florf.getCountFloor() == 0)
                                        {
                                            try {                                     
                                                Registry registry = LocateRegistry.getRegistry(connectRMI.host,connectRMI.port);
                                                EtowInterface obj=(EtowInterface)registry.lookup(connectRMI.regis);
                                                        String townName = tbdulieu.getValueAt(j,1).toString();
                                                        int numberOfFloor = Integer.parseInt(tbdulieu.getValueAt(j,2).toString());
                                                        int id = Integer.parseInt(tbdulieu.getValueAt(j,3).toString());
                                                        obj.EditTown(townName,numberOfFloor,id,"0");
                                                }catch(Exception ex){
                                                        
                                                }
                                                reloadtable();
                                        }
                                        else
                                        {
                                            reloadtable();
                                        }
                                        break;
                                    }
                                }
				
			}														    
		}
    	
   
    }

    private void btnexitActionPerformed(java.awt.event.ActionEvent evt) {
    	setVisible(false);
    }
    
    class MyItemListener implements ItemListener  
    {  
     public void itemStateChanged(ItemEvent e) {  
        Object source = e.getSource();  
        if (source instanceof AbstractButton == false) return;  
        boolean checked = e.getStateChange() == ItemEvent.SELECTED;  
        for(int x = 0, y = tbdulieu.getRowCount(); x < y; x++)  
        {  
        	tbdulieu.setValueAt(new Boolean(checked),x,0);  
        }  
      }  
    }
    
    public static String getA1() {
		return a1;
	}

	public static String getA2() {
		return a2;
	}

	public static String getA3() {
		return a3;
	}
}




